import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from models import Test

class TestPage(webapp.RequestHandler):
  def get(self):
    test_count = Test.all().count()
    test_query = Test.all().order('-date')
    test = test_query.fetch(5)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'test': test,
      'count': test_count,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'test.html')
    self.response.out.write(template.render(path, template_values))

class AddRecord(webapp.RequestHandler):
  def post(self):
    if users.get_current_user():
      owner = users.get_current_user()
    start_number = int(self.request.get('name'))
    total_number = int(self.request.get('total'))
    for i in range(start_number, total_number + start_number):
      tt = Test()
      tt.name = str(i)
      if users.get_current_user():
        tt.owner = owner
      tt.put()
    self.redirect('/test/')

application_test = webapp.WSGIApplication(
  [('/test/', TestPage),
  ('/test/add', AddRecord)],
  debug=True)

def main():
  run_wsgi_app(application_test)

if __name__ == "__main__":
  main()
